/* eslint-disable max-params */
import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { SetupStoreId } from '@/enum';
import { useRouterPush } from '@/hooks/common/router';
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
import { cookieStg, localStg } from '@/utils/storage';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { clearAuthStorage, getToken, getUserInfo } from './shared';

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const routeStore = useRouteStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive(getUserInfo());

  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;

    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo?.roles?.includes(VITE_STATIC_SUPER_ROLE);
  });

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    const authStore = useAuthStore();
    clearAuthStorage();

    authStore.$reset();

    if (!route.meta.constant) {
      await toLogin();
    }

    routeStore.resetStore();
  }

  /**
   * Login
   *
   * @param userName User name
   * @param password Password
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(
    username: string,
    password: string,
    code?: string,
    uuid?: string,
    fetchCaptchCode?: () => any,
    redirect = true
  ) {
    startLoading();

    const { data, error } = await fetchLogin({
      username,
      password,
      code,
      uuid
    });
    const loginToken = data?.data;
    // console.log(, error);
    if (!error) {
      const pass = await loginByToken(loginToken);

      if (pass) {
        await routeStore.initAuthRoute();

        if (redirect) {
          await redirectFromLogin();
        }

        if (routeStore.isInitAuthRoute) {
          // window.$notification?.success({
          //   title: $t('page.login.common.loginSuccess'),
          //   content: $t('page.login.common.welcomeBack', { userName: userInfo?.user.userName }),
          //   duration: 4500
          // });
          (window as any).$message.success($t('page.login.common.loginSuccess'));
        }
      }
    } else {
      resetStore();
      fetchCaptchCode();
    }

    endLoading();
  }

  async function loginByToken(loginToken: Api.Auth.LoginToken) {
    // 1. stored in the localStorage, the later requests need it in headers
    cookieStg.set('smart-authorization', loginToken.access_token);
    // localStg.set('refreshToken', loginToken.refreshToken);

    const { data, error } = await fetchGetUserInfo();
    // console.log(data.data);

    const info = data?.data;
    if (!error) {
      // 2. store user info
      localStg.set('userInfo', info);

      // 3. update store
      token.value = loginToken.access_token;
      Object.assign(userInfo, info);

      return true;
    }

    return false;
  }

  async function featchUserInfo() {
    const { data, error } = await fetchGetUserInfo();
    const info = data?.data;
    if (!error) {
      localStg.set('userInfo', info);
      Object.assign(userInfo, info);
      return true;
    }
    return false;
  }

  return {
    token,
    userInfo,
    isStaticSuper,
    isLogin,
    loginLoading,
    resetStore,
    featchUserInfo,
    login
  };
});
